#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <vector>
#include <string>

#include "Mutex.hpp"

using namespace std;

#define NUM 3

int ticket = 100;

//pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
MutexMoudle::Mutex mutex;

class ThreadData
{
public:
    ThreadData(int number /*,pthread_mutex_t* lock*/)
    {
        _name = "thread-" + to_string(number);
        //   _lock=lock;
    }

    string _name;
    // pthread_mutex_t* _lock;
};

void *SellTicket(void *arg)
{
    ThreadData *id = static_cast<ThreadData *>(arg);
    while (1)
    {
        usleep(100); // 避免饥饿问题，等待几秒，再再次申请锁
        MutexMoudle::LockGuard lockguard(mutex);   // RAII 风格锁
        //   pthread_mutex_lock(id->_lock);
        //    pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket: %d\n", id->_name.c_str(), ticket);
            ticket--;
            //     pthread_mutex_unlock(id->_lock);
            //      pthread_mutex_unlock(&lock);
        }
        else
        {
            //     pthread_mutex_unlock(id->_lock);
            //   pthread_mutex_unlock(&lock);
            break;
        }
    }
    printf("%s quit...\n", id->_name.c_str());
    return nullptr;
}

int main()
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock,nullptr);
    vector<pthread_t> tids; // 方便进行删除，在程序结束后，系统并不会自动调用对象的析构函数，而是直接全部回收，
    vector<ThreadData *> pthread_datas;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        ThreadData *data = new ThreadData(i /*,&lock*/);

        pthread_create(&tid, nullptr, SellTicket, data);
        tids.push_back(tid);
    }
    for (auto tid : tids)
    {
        pthread_join(tid, nullptr);
    }
    for (auto data : pthread_datas)
    {
        delete data;
    }
    // pthread_mutex_destroy(&lock);
    return 0;
}
